const fs = require('fs');
const path = require('path');
const xlsx = require('node-xlsx');
const deleteDir = require('./deleteFile');
const emitter = require('./events');

// 读取 excel 文件
exports.readExcelFile = filename => {
  if (filename && path.extname(filename).slice(1).toLowerCase() !== 'xlsx') {
    return console.error('请选择xlsx文件');
  }
  return xlsx.parse(filename)[0].data;
};

// 写入 excel 文件
exports.writeExcelFile = (data = [], filename = 'export.xlsx') => {
  let excelData = [
    {
      name: 'sheet1',
      data
    }
  ];
  // xlsx 转化成二进制
  const buffer = xlsx.build(excelData);
  // 删除目录已有文件
  deleteDir(path.join(__dirname, '../../output'));
  // 写入文件
  filename = path.join(__dirname, `../../output/${filename}`);
  // fs模块写入文件
  fs.writeFile(filename, buffer, function (err) {
    if (err) {
      emitter.emit('write_event', err);
      console.log('数据写入错误');
      throw err;
    }
    emitter.emit('write_event', '数据写入文件成功');
  });
};
